#import "ChartLyricsLyricsProvider.h"

@implementation ChartLyricsLyricsProvider

- (NSString *) fetchLyricsForSong:(TrackInfo *)track {
	NSString *escapedArtist = [track.artist stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSString *escapedName   = [track.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSString *url = [NSString 
		stringWithFormat:@"http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=%@&song=%@",
		escapedArtist,
		escapedName
	];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest new] autorelease];
	[request setURL:[NSURL URLWithString:url]];
	[request setHTTPMethod:@"GET"];
	
	NSHTTPURLResponse *response = nil;  
	NSError *error = [NSError new];
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  
	if (data == nil) {
		NSLog(@"Request to chartlyrics.com failed with error: %@", [error localizedDescription]);
		return nil;
	}
	
	if ([response statusCode] >= 200 && [response statusCode] < 300) {
		NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:data] autorelease];
		[parser setDelegate:self];
		lyrics = nil;
		gatheringLyrics = NO;
		if (![parser parse])
			return nil;
		
		return lyrics;
	}
	
	NSLog(@"Request to chartlyrics.com gets error code %d", [response statusCode]);
	return nil;
}



- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
	if ([elementName isEqualToString:@"Lyric"]) {
		gatheringLyrics = YES;
		lyrics = [NSString string];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	lyrics = [lyrics stringByAppendingString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	if ([elementName isEqualToString:@"Lyric"])
		gatheringLyrics = NO;
}

- (void) beginFetchLyricsForSong:(TrackInfo *)track {
	// Not implemented
}

@end
